package com.wenx.v3system.modular.cloud.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 系统用户信息控制器
 * 提供用户状态查询、系统统计信息获取、用户会话管理等功能
 * 
 * @author wenx
 */
@Tag(name = "用户信息API", description = "用户状态和系统信息相关接口")
@Slf4j
@RestController
@RequestMapping("/api/userinfo")
public class SysUserInfoController {

    /**
     * 获取用户状态信息
     * 
     * @param session HTTP会话对象
     * @return 用户登录状态和基本信息
     */
    @Operation(summary = "获取用户状态", description = "获取当前用户的登录状态和基本信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/user-status")
    public Map<String, Object> getUserStatus(
            @Parameter(description = "HTTP会话", required = true) HttpSession session) {
        
        String accessToken = (String) session.getAttribute("access_token");
        boolean isLoggedIn = accessToken != null && !accessToken.trim().isEmpty();
        
        if (isLoggedIn) {
            @SuppressWarnings("unchecked")
            Map<String, Object> userInfo = (Map<String, Object>) session.getAttribute("user_info");
            String username = userInfo != null && userInfo.get("username") != null 
                ? userInfo.get("username").toString() 
                : "用户";
            
            return Map.of("isLoggedIn", true, "username", username, "success", true);
        }
        
        return Map.of("isLoggedIn", false, "success", true);
    }

    /**
     * 获取系统统计信息
     * 
     * @return 系统运行统计数据
     */
    @Operation(summary = "获取系统统计", description = "获取系统运行状态和统计信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/system-stats")
    public Map<String, Object> getSystemStats() {
        return Map.of(
            "userCount", 1250,
            "roleCount", 25,
            "systemStatus", "正常",
            "todayVisits", 567,
            "logCount", 1234,
            "currentTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
            "success", true
        );
    }

    /**
     * 保存用户登录信息到会话
     * 
     * @param request 包含用户令牌和信息的请求体
     * @param session HTTP会话对象
     * @return 保存结果
     */
    @Operation(summary = "保存用户会话", description = "将OAuth2令牌和用户信息保存到服务端会话中")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "保存成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/save-user-session")
    public Map<String, Object> saveUserSession(
            @Parameter(description = "用户会话数据", required = true) 
            @RequestBody Map<String, Object> request,
            @Parameter(description = "HTTP会话", required = true) 
            HttpSession session) {
        
        try {
            String accessToken = (String) request.get("accessToken");
            if (accessToken == null) {
                return Map.of("success", false, "error", "缺少访问令牌");
            }
            
            // 保存令牌信息
            session.setAttribute("access_token", accessToken);
            session.setAttribute("refresh_token", request.get("refreshToken"));
            session.setAttribute("token_type", request.get("tokenType"));
            session.setAttribute("expires_in", request.get("expiresIn"));
            
            // 保存用户信息
            @SuppressWarnings("unchecked")
            Map<String, Object> userInfo = (Map<String, Object>) request.get("userInfo");
            if (userInfo != null) {
                session.setAttribute("user_info", userInfo);
                log.info("用户登录成功: {}", userInfo.get("username"));
            }
            
            return Map.of("success", true);
            
        } catch (Exception e) {
            log.error("保存用户session失败", e);
            return Map.of("success", false, "error", "保存session失败: " + e.getMessage());
        }
    }
}
